package cn.virens.web.controller.portal;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.virens.common.RequestUtil;
import cn.virens.web.common.BaseController;
import cn.virens.web.components.beetl.format.ImageFormat;
import cn.virens.web.components.websocket.WebSocketPool;

@Controller
@RequestMapping("/portal/socket")
public class SocketContorller extends BaseController {
	private @Autowired WebSocketPool mWebSocketPool;

	public SocketContorller() {
		super("portal/socket");
	}

	@RequestMapping("index.jspx")
	public String index(HttpServletRequest request, HttpServletResponse response, Model model) {
		this.setAttribute(request, "user", RequestUtil.getValueStr(request, "user"));
		this.setAttribute(request, "password", RequestUtil.getValueStr(request, "password"));

		return returnUrl("index");
	}

	@ResponseBody
	@RequestMapping("test.json")
	public Model test(HttpServletRequest request, HttpServletResponse response, Model model) {
		String group = RequestUtil.getValueStr(request, "group");
		String account = RequestUtil.getValueStr(request, "account");

		JSONObject payload = new JSONObject();
		payload.put("self", false);
		payload.put("success", true);
		payload.put("name", "测试用户");
		payload.put("account", "test");
		payload.put("createTime", DateUtil.now());
		payload.put("avatar", ImageFormat.DEF_AVATAR);
		payload.put("content", RequestUtil.getValueStr(request, "content"));

		if (StrUtil.isNotEmpty(account)) {
			model.addAttribute("data", mWebSocketPool.sendAccount(account, payload));
			model.addAttribute("message", "发送成功");
			model.addAttribute("success", true);
		} else if (StrUtil.isNotEmpty(group)) {
			model.addAttribute("data", mWebSocketPool.sendGroup(group, payload));
			model.addAttribute("message", "发送成功");
			model.addAttribute("success", true);
		} else {
			model.addAttribute("success", false);
			model.addAttribute("message", "没有收信人");
		}

		return model;
	}

}
